import base64
import sys

import cv2
import requests, os, json, threading
from win10toast import ToastNotifier

toaster = ToastNotifier()
url = '[2409:8a1e:3b52:8b30::2]'
global us_id
cap = cv2.VideoCapture(0)

face_detector = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')

face_id = input('\n 输入姓名:')

print('\n 初始化人脸捕获。看着相机，等待 ...')
r = requests.get(f'http://{url}/gtn?name={str(face_id)}')
r = r.text
r = json.loads(r)
if r['code'] == 200:
    us_id = int(r['id'])
    toaster.show_toast("note", f"got id -> ok ! Your id is {us_id}")
# else
count = 0



while True:

    # 从摄像头读取图片

    sucess, img = cap.read()

    # 转为灰度图片

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 检测人脸

    faces = face_detector.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + w), (255, 0, 0))
        count += 1
        dir = ".$~tmp/User." + str(face_id) + '.' + str(count) + '.jpg'
        # 保存图像
        cv2.imwrite(dir, gray[y: y + h, x: x + w])

        cv2.imshow('image', img)
        with open(dir, 'rb') as f:
            # noinspection PyRedeclaration
            imge: bytes = f.read()
            imge = base64.b64encode(imge)
            body = {'id': us_id, 'pic': imge}
            r = requests.post(url=f'http://{url}/up_img', data=body).json()
            if r['code'] == 200:
                pass
            else:
                toaster.show_toast("error", "unknown error")
                sys.exit(1)
        os.remove(dir)
    # 保持画面的持续。

    k = cv2.waitKey(1)

    if k == 27:  # 通过esc键退出摄像
        break

    elif count >= 1000:  # 得到1000个样本后退出摄像
        break
# 关闭摄像头
cap.release()
cv2.destroyAllWindows()
toaster.show_toast("note", "完成")
sys.exit(0)
